package com.xuecheng.content.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper,CourseBase> implements CourseBaseInfoService {

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //log.info("执行到这了吗");

        Page<CourseBase> basePage = lambdaQuery()
                .like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()) , CourseBase::getName, queryCourseParamsDto.getCourseName())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus())
                .page(new Page<>(pageParams.getPageNo(),pageParams.getPageSize())); //pageParams.getPageNo(), pageParams.getPageSize()
        //log.info("执行到这了吗");
        return new PageResult<>(basePage.getRecords(),basePage.getTotal(),pageParams.getPageNo(),pageParams.getPageSize());
    }

    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(AddCourseDto dto,Long companyId) {
        //1.数据合法性校验(使用JSR 303校验,手动校验暂时注释掉)
//        if (StringUtils.isBlank(dto.getName())) {
//            throw new RuntimeException("课程名称为空");
//        }
//
//        if (StringUtils.isBlank(dto.getMt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
//            throw new RuntimeException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new RuntimeException("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new RuntimeException("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new RuntimeException("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new RuntimeException("收费规则为空");
//        }
        //2.添加课程基础信息到 course_base表
        CourseBase courseBaseNew = new CourseBase();
        BeanUtils.copyProperties(dto,courseBaseNew);

        //设置审核状态 默认'未提交'(202002)
        courseBaseNew.setAuditStatus("202002");
        //设置发布状态 默认'未发布'(203001)
        courseBaseNew.setStatus("203001");
        //机构id
        courseBaseNew.setCompanyId(companyId);
        //添加时间
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //课程基本信息上传数据库
        boolean reslut = this.save(courseBaseNew);
        if(!reslut){
            throw new RuntimeException("新增课程失败");
        }

        //3.添加课程营销基础信息到 course_market表

        //获取新增课程id(在课程新增成功后会回写课程id到courseBaseNew)
        Long id = courseBaseNew.getId();
        CourseMarket courseMarketNew = new CourseMarket();
        courseMarketNew.setId(id);
        //dto 拷贝数据到 courseMarketNew
        BeanUtils.copyProperties(dto,courseMarketNew);

        //存入课程营销信息到 CourseMarket
        int i= saveCourseMarket(courseMarketNew);
        if(i <= 0){
            throw new RuntimeException("新增课程营销信息失败");
        }

        //4.查询 当前新增的课程基本信息和营销信息返回数据 返回类'CourseBaseInfoDto'
        return getCourseBaseInfo(id);
    }

    private int saveCourseMarket(CourseMarket courseMarketNew) {
        //数据合法性校验

        //收费规则是否为空
        /*
            收费规则是否为空上方新增课程已经做过校验可以省略!!!
        */
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new RuntimeException("收费规则没有选择");
        }
        //收费规则为'收费'的 现价 'price' 校验
        if(charge.equals("201001")){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue()<=0){
                throw new RuntimeException("课程为收费价格不能为空且必须大于0");
            }
        }

        //根据id查询course_market表,如果有数据则更新 没有则新增
        Long id = courseMarketNew.getId();
        CourseMarket courseMarketObj = courseMarketMapper.selectById(id);
        if(courseMarketObj == null){
            //新增
            return courseMarketMapper.insert(courseMarketNew);
        }else {
            //修改
            BeanUtils.copyProperties(courseMarketNew,courseMarketObj);
            return courseMarketMapper.updateById(courseMarketObj);
        }

    }

    public CourseBaseInfoDto getCourseBaseInfo(long courseId){

        //根据id 查询课程基本信息
        /*
        * 如果查不到课程基本信息,则直接返回,
        * */
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        //根据id 查询课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //健壮性判断(校验课程id)
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = this.getById(courseId);
        if(courseBase == null){
            throw new XueChengPlusException("课程不存在");
        }

        //健壮性判断(校验只能修改本机构课程)
        if(!courseBase.getCompanyId().equals(companyId)){
            throw new XueChengPlusException("本机构只能修改本机构的课程");
        }

        //封装课程基本信息
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        //更新课程基本信息
        this.updateById(courseBase);

        //封装营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);

        //更新课程营销信息
        courseMarketMapper.updateById(courseMarket);

        //查询课程信息(基本信息和营销信息)
        CourseBaseInfoDto courseBaseInfo = this.getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

    @Override
    @Transactional
    public void deleteCourseBase(Long id) { //课程id
        CourseBase courseBase = this.getById(id);

        if(courseBase == null){
            throw new XueChengPlusException("该课程为空,无法删除");
        }

        //不为空,则判断课程审核状态是否未提交以外
        String auditStatus = courseBase.getAuditStatus();
        if(!"202002".equals(auditStatus)){
            throw new XueChengPlusException("该课程审核状态不为'未提交',无法删除");
        }

        //到此表示该课程审核状态为:未提交可以进行课程删除
        //删除课程基本信息
        this.removeById(id);

        //删除营销信息(注:课程营销信息和课程基本信息为一对一关系,二者id一致)
        courseMarketMapper.deleteById(id);

        //删除课程计划 课程 和 课程计划为一对多的关系
        LambdaQueryWrapper<Teachplan> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Teachplan::getCourseId,id);
        int deleteCount1 = teachplanMapper.delete(wrapper1);
        log.info("删除了{}个课程计划记录", deleteCount1);

        //删除课程教师信息 课程 和 课程教师信息一对多的关系
        LambdaQueryWrapper<CourseTeacher> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(CourseTeacher::getCourseId,id);
        int deleteCount2 = courseTeacherMapper.delete(wrapper2);
        log.info("删除了{}个课程教师信息记录", deleteCount2);
    }
}
